// 中间件 处理和微信交互的部分

'use strict'
var sha1 = require('sha1');

var Promise = require('bluebird')
var request = Promise.promisify(require('request'));

var prefix = "https://api.weixin.qq.com/cgi-bin/"
var api = {
    accessToken: prefix + "token?grant_type=client_credential"
}

// 构造函数
function WeChat(opts) {
    var that = this;
    this.appID = opts.appID;
    this.appSecret = opts.appSecret;
    this.getAccessToken = opts.getAccessToken;
    this.saveAccessToken = opts.saveAccessToken;
    this.getAccessToken().then(
        // 获取并验证access_token是否有效
        function (data) {
            try {
                data = JSON.stringify(data)
            } catch (error) {
                return that.updateAccessToken()
            }
            if (that.isValidAccessToken(data)) {
                Promise.resolve(data)
            } else {
                return that.updateAccessToken()
            }
        }).then(function (data) {
        // 合法的data
        that.access_token = data.access_token;
        that.expires_in = data.expires_in;
        that.saveAccessToken(data);
    });
}

WeChat.prototype.isValidAccessToken = function (data) {
    console.log("data", data);
    
    if (!data || !data.access_token || !data.expires_in) {
        return false;
    }
    var access_token = data.access_token;
    var expires_in = data.expires_in;
    var now = (new Date().getTime());
    if (now < expires_in) {
        return true
    } else {
        return false
    }
}
WeChat.prototype.updateAccessToken = function (data) {
    var appID = this.appID;
    var appSecret = this.appSecret;
    var url = api.accessToken + "&appid=" + appID + "&appSecret=" + appSecret;

    return new Promise(function (resolve, reject) {
        request({
            url: url,
            json: true
        }).then(function (response) {

            var data = response[1];
            console.log("aaa", data);
            var now = (new Date().getTime());
            var expires_in = now + (data.expires_in ? (data.expires_in - 20) : '') * 1000;
            data.expires_in = expires_in;
            resolve(data)
        });
    })


}



module.exports = function (opts) {
    var weChat = new WeChat(opts)
    // 域名验证
    return function* next() {
        console.log(this.query);

        var token = opts.token;
        var signature = this.query.signature;
        var nonce = this.query.nonce;
        var timestamp = this.query.timestamp;
        var echostr = this.query.echostr;
        var str = [token, timestamp, nonce].sort().join('');
        var sha = sha1(str);
        if (sha === signature) {
            this.body = echostr + '';
        } else {
            this.body = 'wrong'
        }
    }
}